import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/one-oj/login'
    },
    {
      path: '/one-oj/login',
      name: 'Login',
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/one-oj/layout',
      name: 'Layout',
      component: () => import('@/views/Layout.vue'),
      children: [
        {
          path: 'question',
          name: 'Question',
          component: () => import('@/views/Question.vue')
        },
        {
          path: 'exam',
          name: 'Exam',
          component: () => import('@/views/Exam.vue')
        },
        {
          path: 'updateExam',
          name: 'updateExam',
          component: () => import('@/views/UpdateExam.vue')
        },
        {
          path: 'cuser',
          name: 'Cuser',
          component: () => import('@/views/Cuser.vue')
        }
      ]
    }
  ]
})

// 注册一个全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  // 存在 token 的情况
  if (userStore.token) {
    if (to.path === '/one-oj/login') {
      next({ path: '/one-oj/layout' })
    } else {
      next()
    }
  } else {
    if (to.path !== '/one-oj/login') {
      next({ path: '/one-oj/login' })
    } else {
      next()
    }
  }
})

export default router
